﻿#region

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Aspose.Cells;
using DevLib.ExtensionMethods;
using DevLib.ModernUI.Forms;
using Microsoft.Win32;
using Newtonsoft.Json;

#endregion

namespace IE设置
{
    public partial class Form1 : ModernForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            modernLabel1.Text = @"作者：魏绍扬　联系电话:296089　本软件修改内容:IE7以上兼容性站点,可信任站点,可信任站点配置.";
            GetDb();
            GetFilters();
            GetIeKey();
            Console.WriteLine(Environment.UserName);
            Text = (Environment.Is64BitOperatingSystem ? "64位系统" : "32位系统") + @"——IE版本号：" + IeVer;
            GetRanges();
        }

        [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
        private void GetIeKey()
        {
            try
            {
                var internetexplorer = RegistryKey
                    .OpenBaseKey(RegistryHive.LocalMachine,
                        Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32)
                    .OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer");

                var HKCU = RegistryKey
                    .OpenBaseKey(RegistryHive.CurrentUser,
                        Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
                var ieSetting = HKCU.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings");
                if (internetexplorer != null && ieSetting != null)
                {
                    IeSettings = ieSetting;
                    var svcVersion = internetexplorer.GetValue("svcVersion");
                    var version = internetexplorer.GetValue("Version");
                    IeVer = new Version(version.ToString());
                    if (svcVersion!=null)
                    {
                        IeVer = new Version(svcVersion.ToString());
                    }
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            MessageBox.Show(@"获取IE注册表信息失败！");
            Environment.Exit(0);
        }

        [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
        private Dictionary<string, List<RegValItem>> GetRanges()
        {
            var rangesKey = IeSettings.OpenSubKey("ZoneMap\\Ranges", true);
            var rangesSubKeyNames = rangesKey.GetSubKeyNames();
            Dictionary<string, List<RegValItem>> ranges = new Dictionary<string, List<RegValItem>>();
            foreach (string rangesSubKeyName in rangesSubKeyNames)
            {
                var subKey = rangesKey.OpenSubKey(rangesSubKeyName);
                var rangeValueNames = subKey.GetValueNames();
                ranges.Add(rangesSubKeyName, new List<RegValItem>());
                foreach (string rangeValueName in rangeValueNames)
                {
                    RegValItem item = new RegValItem();
                    item.Name = rangeValueName;
                    item.Value = subKey.GetValue(rangeValueName);
                    item.Type = subKey.GetValueKind(rangeValueName);
                    ranges[rangesSubKeyName].Add(item);
                }
            }
            return ranges;
        }

        private void SetRanges(Dictionary<string, List<RegValItem>> ranges)
        {
            var rangesKey = IeSettings.OpenSubKey("ZoneMap\\Ranges", true);
            foreach (KeyValuePair<string, List<RegValItem>> range in ranges)
            {
                rangesKey.CreateSubKey(range.Key);
                var rangeSubKey = rangesKey.OpenSubKey(range.Key, true);
                foreach (RegValItem item in range.Value)
                    rangeSubKey.SetValue(item.Name, item.Value, item.Type);
            }
            rangesKey.Close();
        }

        private List<RegValItem> GetSettings()
        {
            var settings = new List<RegValItem>();
            var settingKey = IeSettings.OpenSubKey("Zones\\2", true);
            foreach (string name in settingKey.GetValueNames())
            {
                RegValItem item = new RegValItem();
                item.Name = name;
                item.Value = settingKey.GetValue(name);
                item.Type = settingKey.GetValueKind(name);
                settings.Add(item);
            }
            return settings;
        }

        private void SetSettings(List<RegValItem> settings)
        {
            var settingKey = IeSettings.OpenSubKey("Zones\\2", true);
            foreach (RegValItem item in settings)
                settingKey.SetValue(item.Name, item.Value, item.Type);
        }

        private void modernButton1_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            var ranges = GetRanges();
            var settings = GetSettings();
            var cfg = new Cfg();
            cfg.Items = settings;
            cfg.Ranges = ranges;
            if (IeVer.Major > 7)
            {
                Filter filter = new Filter();
                cfg.filters = filter.GetDomains();
                foreach (var filterstr in cfg.filters)
                    listView1.Items.Add("兼容性站点保存成功：" + filterstr);
            }
            File.Delete("settings.json");
            File.WriteAllText("settings.json", JsonConvert.SerializeObject(cfg), Encoding.UTF8);
          
            foreach (RegValItem item in cfg.Items)
            {
                var db = DbList.Find(s => s.Code == item.Name);
                if (db == null)
                    continue;
                listView1.Items.Add(db.CodeStr + ":" + db.Items.Find(s => s.Value == item.Value.ToString()).Name);
            }


            listView1.Items.Add("保存成功，文件保存在当前目录settings.json");
        }

        private void modernButton2_Click(object sender, EventArgs e)
        {
            var msg=
            MessageBox.Show(@"结束所有IE进程？", @"警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                MessageBoxDefaultButton.Button1);
            if (msg==DialogResult.Yes)
            {
                Cmd.Run("taskkill /f /im iexplore.exe");
            }

            listView1.Items.Clear();
            var cfg = JsonConvert.DeserializeObject<Cfg>(File.ReadAllText("settings.json"));


            var rangesKey = IeSettings.OpenSubKey("ZoneMap\\Ranges", true);
            var subkeyNames = rangesKey.GetSubKeyNames();
            foreach (string subkeyName in subkeyNames)
                rangesKey.DeleteSubKeyTree(subkeyName);
            if (IeVer.Major > 7)
            {
                Filter filter = new Filter();
                foreach (string filterDomain in filter.GetDomains())
                    filter.RemoveUserFilter(filterDomain);


                foreach (string cfgFilter in cfg.filters)
                {
                    filter.AddNewSiteToCompatibilityViewList(cfgFilter);

                    listView1.Items.Add("兼容性站点还原成功：" + cfgFilter);
                }
            }
            SetRanges(cfg.Ranges);
            SetSettings(cfg.Items);
            foreach (RegValItem item in cfg.Items)
            {
                var db = DbList.Find(s => s.Code == item.Name);
                if (db == null)
                    continue;
                listView1.Items.Add(db.CodeStr + ":" + db.Items.Find(s => s.Value == item.Value.ToString()).Name);
            }


            listView1.Items.Add("还原成功");
        }

        public void GetDb()
        {
            Workbook book;
            if (File.Exists("ie.xlsx"))
            {
                book = new Workbook("ie.xlsx");
            }
            else if(File.Exists("ie.xls"))
            {
                book = new Workbook("ie.xls");
            }
            else
            {
                book = new Workbook(new MemoryStream(Properties.Resources.ie));
            }
            Worksheet sheet = book.Worksheets[0];
            var maxcol = sheet.Cells.MaxDataColumn;
            var maxrow = sheet.Cells.MaxDataRow;

            for (int i = 1; i <= maxrow; i++)
            {
                Db db = new Db();
                db.Code = sheet.Cells[i, 0].Value.ToString();
                db.CodeStr = sheet.Cells[i, 1].Value.ToString();
                db.CodeType = sheet.Cells[i, 2].Value.ToString();
                db.Items = new List<DbItem>();
                for (int j = 3; j <= maxcol; j++)
                {
                    if (sheet.Cells[i, j].Value == null)
                        continue;
                    if (string.IsNullOrWhiteSpace(sheet.Cells[i, j].Value.ToString()))
                        continue;
                    db.Items.Add(new DbItem(sheet.Cells[0, j].Value.ToString(), sheet.Cells[i, j].Value.ToString(),
                        RegistryValueKind.DWord));
                }

                DbList.Add(db);
            }
            book.TryDispose();
        }

        public void GetFilters()
        {
           
            Workbook book;
            if (File.Exists("ie.xlsx"))
            {
                book = new Workbook("ie.xlsx");
            }
            else if (File.Exists("ie.xls"))
            {
                book = new Workbook("ie.xls");
            }
            else
            {
                book = new Workbook(new MemoryStream(Properties.Resources.ie));
            }
            Worksheet sheet = book.Worksheets[1];
            var maxrow = sheet.Cells.MaxDataRow;
            for (int i = 0; i <= maxrow; i++)
            {
                string val = sheet.Cells[i, 0].Value.ToString();
                if (!string.IsNullOrWhiteSpace(val))
                {
                    FilterList.Add(val);
                }
            }
        }

        private void modernButton3_Click(object sender, EventArgs e)
        {
            var msg =
              MessageBox.Show(@"结束所有IE进程？", @"警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                  MessageBoxDefaultButton.Button1);
            if (msg == DialogResult.Yes)
            {
                Cmd.Run("taskkill /f /im iexplore.exe");
            }
            listView1.Items.Clear();
            List<RegValItem> tobeItems = new List<RegValItem>();
            var settings = GetSettings();
            foreach (RegValItem item in settings)
            {
                var it = DbList.Find(s => s.Code == item.Name);
                if (it == null)
                    continue;
                item.Value = it.Items.Find(t => t.Name == it.Items.Find(s => s.Name == "IE设置").Value).Value;
                tobeItems.Add(item);


                var db = DbList.Find(s => s.Code == item.Name);
                if (db == null)
                    continue;
                listView1.Items.Add(db.CodeStr + ":" + db.Items.Find(s => s.Value == item.Value.ToString()).Name);
            }
            SetSettings(tobeItems);
            var rangesKey = IeSettings.OpenSubKey("ZoneMap\\Ranges", true);
            var subkeyNames = rangesKey.GetSubKeyNames();
            foreach (string subkeyName in subkeyNames)
                rangesKey.DeleteSubKeyTree(subkeyName);
            var ranges = new Dictionary<string, List<RegValItem>>();
            ranges.Add("Range1", new List<RegValItem>());
            RegValItem item1 = new RegValItem();
            item1.Name = "*";
            item1.Value = "2";
            item1.Type = (RegistryValueKind) 4;
            ranges["Range1"].Add(item1);
            RegValItem item2 = new RegValItem();
            item2.Name = ":Range";
            item2.Value = "*.*.*.*";
            item2.Type = (RegistryValueKind) 1;
            ranges["Range1"].Add(item2);

            SetRanges(ranges);
            listView1.Items.Add("可信任站点添加*.*.*.*");
            if (IeVer.Major > 7)
            {
                Filter filter = new Filter();
                foreach (string filterDomain in filter.GetDomains())
                    filter.RemoveUserFilter(filterDomain);
                foreach (string s in FilterList)
                {
                    filter.AddNewSiteToCompatibilityViewList(s);
                }
                listView1.Items.Add("添加兼容性站点成功");
            }

            listView1.Items.Add("配置成功");
        }

        [Serializable]
        public class RegValItem
        {
            public string Name { get; set; }
            public object Value { get; set; }
            public RegistryValueKind Type { get; set; }
        }

        [Serializable]
        public class Cfg
        {
            public Dictionary<string, List<RegValItem>> Ranges { get; set; }
            public List<RegValItem> Items { get; set; }
            public string[] filters { get; set; }
        }

        public class Db
        {
            public string Code { get; set; }
            public string CodeStr { get; set; }
            public string CodeType { get; set; }
            public List<DbItem> Items { get; set; }
        }

        public class DbItem
        {
            public DbItem(string name, string value, RegistryValueKind type)
            {
                Name = name;
                Value = value;
                Type = type;
            }

            public string Name { get; set; }
            public string Value { get; set; }
            public RegistryValueKind Type { get; set; }
        }

        #region field

        private Version IeVer { get; set; }
        private RegistryKey IeSettings { get; set; }
        public readonly List<Db> DbList = new List<Db>();
        public readonly List<string> FilterList = new List<string>();
        #endregion
    }
}